/// ASR FFI 使用示例
///
/// 这个示例展示了如何使用 asr_ffi.dart 进行语音识别
///
/// 特点：
/// 1. 完全基于 assets 目录中的文件，不依赖外部文件
/// 2. 自动提取和管理 DLL 及模型文件
/// 3. 支持离线和在线识别模式
/// 4. 提供详细的调试信息
library;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'dart:io';
import 'asr_ffi.dart';

class AsrExampleWidget extends StatefulWidget {
  const AsrExampleWidget({super.key});

  @override
  State<AsrExampleWidget> createState() => _AsrExampleWidgetState();
}

class _AsrExampleWidgetState extends State<AsrExampleWidget> {
  String _status = '未初始化';
  String _recognitionResult = '';
  bool _isProcessing = false;
  final List<String> _debugInfo = [];

  @override
  void initState() {
    super.initState();
    _initializeAsr();
  }

  /// 初始化 ASR 系统
  Future<void> _initializeAsr() async {
    setState(() {
      _status = '正在初始化...';
      _debugInfo.add('开始初始化 ASR 系统');
    });

    try {
      await AsrFFI.initialize();

      setState(() {
        _status = '初始化完成';
        _debugInfo.add('ASR 系统初始化成功');
      });

      // 获取调试信息
      final debugInfo = AsrFFI.getDebugInfo();
      setState(() {
        _debugInfo.add('工作目录: ${debugInfo['workRoot']}');
        _debugInfo.add('DLL目录: ${debugInfo['dllDir']}');
        _debugInfo.add('模型目录: ${debugInfo['modelDir']}');
      });
    } catch (e) {
      setState(() {
        _status = '初始化失败: $e';
        _debugInfo.add('初始化失败: $e');
      });
    }
  }

  /// 从 assets 复制音频文件到临时目录
  Future<String> _copyAssetToTemp(String assetPath) async {
    final tempDir = await getTemporaryDirectory();
    final fileName = path.basename(assetPath);
    final targetPath = path.join(tempDir.path, fileName);

    final file = File(targetPath);
    if (!await file.exists()) {
      final bytes = await rootBundle.load(assetPath);
      await file.writeAsBytes(bytes.buffer.asUint8List());
    }

    return targetPath;
  }

  /// 执行离线识别
  Future<void> _performOfflineRecognition(String assetPath) async {
    if (_isProcessing) return;

    setState(() {
      _isProcessing = true;
      _status = '正在进行离线识别...';
      _debugInfo.add('开始离线识别: $assetPath');
    });

    try {
      // 复制音频文件到临时目录
      final wavPath = await _copyAssetToTemp(assetPath);
      setState(() {
        _debugInfo.add('音频文件路径: $wavPath');
      });

      // 执行识别
      final result = await AsrFFI.performOfflineRecognition(wavPath);

      setState(() {
        _recognitionResult = result;
        _status = '离线识别完成';
        _debugInfo.add('识别结果: $result');
      });
    } catch (e) {
      setState(() {
        _status = '离线识别失败: $e';
        _debugInfo.add('离线识别失败: $e');
      });
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  /// 执行在线识别
  Future<void> _performOnlineRecognition(String assetPath) async {
    if (_isProcessing) return;

    setState(() {
      _isProcessing = true;
      _status = '正在进行在线识别...';
      _debugInfo.add('开始在线识别: $assetPath');
    });

    try {
      // 复制音频文件到临时目录
      final wavPath = await _copyAssetToTemp(assetPath);
      setState(() {
        _debugInfo.add('音频文件路径: $wavPath');
      });

      // 执行识别
      final result = await AsrFFI.performOnlineRecognition(wavPath);

      setState(() {
        _recognitionResult = result;
        _status = '在线识别完成';
        _debugInfo.add('识别结果: $result');
      });
    } catch (e) {
      setState(() {
        _status = '在线识别失败: $e';
        _debugInfo.add('在线识别失败: $e');
      });
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  /// 清除调试信息
  void _clearDebugInfo() {
    setState(() {
      _debugInfo.clear();
      _recognitionResult = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ASR FFI 示例'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 状态显示
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('状态', style: Theme.of(context).textTheme.titleMedium),
                    const SizedBox(height: 8),
                    Text(_status),
                    if (_isProcessing)
                      const Padding(
                        padding: EdgeInsets.only(top: 8.0),
                        child: LinearProgressIndicator(),
                      ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 识别结果
            if (_recognitionResult.isNotEmpty)
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '识别结果',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      const SizedBox(height: 8),
                      Text(
                        _recognitionResult,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

            const SizedBox(height: 16),

            // 操作按钮
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('操作', style: Theme.of(context).textTheme.titleMedium),
                    const SizedBox(height: 16),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton.icon(
                          onPressed: _isProcessing
                              ? null
                              : () => _performOfflineRecognition(
                                  'assets/audios/asr_example_zh.wav',
                                ),
                          icon: const Icon(Icons.mic_none),
                          label: const Text('离线识别 (中文)'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _isProcessing
                              ? null
                              : () => _performOnlineRecognition(
                                  'assets/audios/asr_example_zh.wav',
                                ),
                          icon: const Icon(Icons.mic),
                          label: const Text('在线识别 (中文)'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _isProcessing
                              ? null
                              : () => _performOfflineRecognition(
                                  'assets/audios/vad_example.wav',
                                ),
                          icon: const Icon(Icons.mic_none),
                          label: const Text('离线识别 (VAD)'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _clearDebugInfo,
                          icon: const Icon(Icons.clear),
                          label: const Text('清除信息'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 调试信息
            Expanded(
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '调试信息',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      const SizedBox(height: 8),
                      Expanded(
                        child: Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(8.0),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: SingleChildScrollView(
                            child: Text(
                              _debugInfo.isEmpty
                                  ? '暂无调试信息'
                                  : _debugInfo.join('\n'),
                              style: const TextStyle(
                                fontFamily: 'monospace',
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
